import { saveCall, saveCallAsync, sleep } from "../utils/utils"

const _checkStock = async (productId)=>{
	//模拟服务器请求延迟
	await sleep(500)
	return {
		stock: 100
	}
}

const _makeOrder = async (productId, num)=>{
	//模拟服务器请求延迟
	await sleep(500)
	return {
		orderId: '123456789'
	}
}

const _getPaymentUrl = async (orderId)=>{
	await sleep(500)
	
	return 'http://www.baidu.com'
}

//模拟下单流程
export const makeOrder = async (productId, num)=>{
	//1，向服务器查询商品库存
	const stock = await _checkStock(productId)
	
	//2，向服务器发起下单请求
	const order = await _makeOrder(productId, numm)
	
	//3, 向服务器获取支付码地址
	const url = await _getPaymentUrl(order.orderId)
	
	return url
}

const _checkStock1 = (productId, cb)=>{
	//模拟服务器请求延迟
	setTimeout(()=>{
		cb({
			stock: 100
		})
	}, 500)
}

const _makeOrder1 = (productId, num, cb)=>{
	//模拟服务器请求延迟
	setTimeout(()=>{
		cb({
			orderId: '123456789'
		})
	}, 500)
}

const _getPaymentUrl1 = (orderId, cb)=>{
	//模拟服务器请求延迟
	setTimeout(()=>{
		cb('http://www.baidu.com')
	}, 500)
}


export const makeOrder = (productId, num, cb)=>{
	//1，向服务器查询商品库存
	_checkStock1(productId, (stock)=>{
		//2，向服务器发起下单请求
		_makeOrder1(productId, num, (order)=>{
			//3, 向服务器获取支付码地址
			_getPaymentUrl1(order.orderId, (url)=>{
				cb(url)
			})
		})
	})
}




const _run = (a, b, c)=>{
	console.log('run')
}
const _runAsync = async (a, b, c)=>{
	await sleep(100)
	console.log('run')
}
export const catchError1 = ()=>{
	try{
		_run()
	}catch(err){
		console.log('err', err)
	}
}
export const catchErrorAsync1 = async ()=>{
	try{
		await _runAsync()
	}catch(err){
		console.log('err', err)
	}
}



export const catchError2 = ()=>{
	const [err, resp] = saveCall(_run, null, a, b, c)
	if(!!err){
		console.log('err', err)
	}
}

export const catchErrorAsync2 = async ()=>{
	const [err, resp] = await saveCallAsync(_runAsync null, a, b, c)
	if(!!err){
		console.log('err', err)
	}
}
